package com.marst.first.interceptor;


import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.marst.first.Exception.TokenVerifyException;
import com.marst.first.utils.RedisUtils;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


import java.util.Enumeration;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName LogCostInterceptor
 * @Author Administrator
 * @Date 2021/10/12 0012 下午 10:13
 * @Description TODO 拦截器
 * @Version 1.0
 **/
@Slf4j
@Component
public class AdminInterceptor implements HandlerInterceptor {


    private static RedisUtils redisUtils;

    @Autowired
    public void setRedisService(RedisUtils redisUtils) {AdminInterceptor.redisUtils=redisUtils;}

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.info("==============request URL:{}",request.getRequestURI());
        String token = request.getHeader("token");
        String account = request.getHeader("account");
        log.info("token:{},account:{}", token, account);
        if (StringUtils.isBlank(token)||StringUtils.isBlank(account)) {
            log.info("=====请求失败=====");
            throw new TokenVerifyException();
        }
        Object redisToken = redisUtils.get(account);
        String stringRedisToken = String.valueOf(redisToken);
        if (StringUtils.isNotEmpty(token)&&token.equals(stringRedisToken)){
            return true;
        }else {
            log.info("=====请求失败=====");
            throw new TokenVerifyException();
        }
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        log.info("method completion info:{}",request.getRequestURI());
    }
}
